$(function () {
    $("#schedule_datagrid").datagrid({
        fit: true,
        rownumbers: true,
        singleSelect: true,
        pagination: true,
        pageSize: 10,
        url: 'schedule/list/all',
        toolbar: [
            {
                text: '新增',
                iconCls: 'icon-add',
                handler: function () {
                    if (endEditing()) {
                        var newRowData = {
                            id: 0,
                            restrictionNumber: 0,
                            restrictionGrade: "",
                            blackListId: 0,
                            blackListName: "",
                            courseId: 0,
                            courseName: "",
                            classroomId: 0,
                            classroomLocation: "",
                            teacherId: 0,
                            teacherName: "",
                            required: 0,
                            firstTerm: 0,
                            secondTerm: 0,
                            firstSection: 0,
                            secondSection: 0,
                            thirdSection: 0,
                            firstLesson: 0,
                            secondLesson: 0,
                            thirdLesson: 0,
                            forthLesson: 0,
                            fifthLesson: 0,
                            sixthLesson: 0,
                            seventhLesson: 0,
                            eighthLesson: 0,
                            monday: 0,
                            tuesday: 0,
                            wednesday: 0,
                            thursday: 0,
                            friday: 0,
                            saturday: 0,
                            sunday: 0
                        };
                        $.ajax({
                            type: 'POST',
                            data: newRowData,
                            url: "schedule/add",
                            dataType: "json",
                            cache: false,
                            success: function (data) {
                                newRowData.id = data;
                                $('#schedule_datagrid').oneTime("0.2s", function () {
                                    $('#schedule_datagrid').datagrid('appendRow', newRowData);
                                    $('#schedule_datagrid').datagrid("acceptChanges");
                                    editIndex = $('#schedule_datagrid').datagrid('getRows').length - 1;
                                    $('#schedule_datagrid').datagrid('selectRow', editIndex)
                                        .datagrid('beginEdit', editIndex);
                                    initialPropertyData(newRowData);
                                });
                            },
                            error: function (jqXHR, textStatus, errorThrown) {
                                $.messager.alert("操作提示", "添加数据异常:[" + jqXHR.statusText + "]", "error");
                            }
                        });
                    }
                }
            },
            '-',
            {
                text: '删除',
                iconCls: 'icon-remove',
                handler: function () {
                    if (editIndex == undefined) {
                        $.messager.alert("操作提示", "请选择你需要删除的行！", 'warning');
                        return;
                    }
                    $.messager.confirm("删除确认", "删除排课信息将会导致相关的选课所有信息将会丢失，请确认删除？", function (r) {
                        if (r) {
                            var deleteId = $('#schedule_datagrid').datagrid('getData').rows[editIndex].id;
                            $.ajax({
                                type: 'POST',
                                url: "schedule/delete/" + deleteId,
                                dataType: "json",
                                cache: false,
                                success: function (data) {
                                    $.messager.alert("操作提示", "数据删除成功！", "info");
                                    $('#schedule_datagrid').oneTime("0.2s", function () {
                                        $('#schedule_datagrid').datagrid('cancelEdit', editIndex)
                                            .datagrid('deleteRow', editIndex);
                                        $('#schedule_datagrid').datagrid("acceptChanges");
                                        var propertyRows = {
                                            total: 0,
                                            rows: []
                                        };
                                        $("#schedule_property").propertygrid("loadData", propertyRows);
                                        editIndex = undefined;
                                    });
                                },
                                error: function (jqXHR, textStatus, errorThrown) {
                                    $.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
                                }
                            });
                        }
                    });
                }
            },
            '-',
            {
                text: '保存',
                iconCls: 'icon-save',
                handler: function () {
                    if (endEditing()) {
                        var propertyRows = {
                            total: 0,
                            rows: []
                        };
                        $("#schedule_property").propertygrid("loadData", propertyRows);
                        $.messager.alert("操作提示", "数据保存成功！", "info");
                    }
                }
            },
            '-',
            {
                text: '刷新',
                iconCls: 'icon-reload',
                handler: function () {
                   if(endEditing()){
                       $("#schedule_datagrid").datagrid("options").pageNumber = 1;
                       $("#schedule_datagrid").datagrid('getPager').pagination({pageNumber: 1});
                       $('#schedule_datagrid').datagrid({
                           url: 'schedule/list/all'
                       });
                   }
                }
            },
            '-',
            {
                text: '查找',
                iconCls: 'icon-search',
                handler: function () {
                    $("#search_dialog").dialog({
                        title: "查找排课信息",
                        iconCls: 'icon-search',
                        width: 350,
                        height: 180,
                        modal: true,
                        buttons: [
                            {
                                text: '提交',
                                iconCls: 'icon-ok',
                                handler: function () {
                                    var courseName = $("#search_course").val();

                                    var teacherName = $("#search_teacher").val();
                                    $("#schedule_datagrid").datagrid("options").pageNumber = 1;
                                    $("#schedule_datagrid").datagrid('getPager').pagination({pageNumber: 1});

                                    $('#schedule_datagrid').datagrid({
                                        url: 'schedule/list/conditions',
                                        queryParams: {
                                            courseName: $("#search_course").val(),
                                            teacherName: $("#search_teacher").val()
                                        }
                                    });
                                    $("#search_course").val("");
                                    $("#search_teacher").val("");
                                    $("#search_dialog").dialog("close");
                                }
                            }
                        ]
                    });

                    $("#search_dialog").dialog("open");
                }
            },
            '-',
            {
                text: "管理开课班级",
                iconCls: "icon-edit",
                handler: function () {
                    if (editIndex == undefined) {
                        $.messager.alert("操作提示", "请选择你需要管理的行！", 'warning');
                        return;
                    }
                    var courseSchedule = $('#schedule_datagrid').datagrid('getData').rows[editIndex];
                    $("#schedule_class_management_dialog").dialog({
                        title: courseSchedule.courseName + '(' + courseSchedule.teacherName + ')-开课班级管理',
                        width: 400,
                        height: 200,
                        closed: false,
                        cache: false,
                        modal: true
                    });
                    $("#schedule_class_management_datagrid").datagrid({
                        fit: true,
                        rownumbers: true,
                        singleSelect: true,
                        url: "schedule/list/" + courseSchedule.id + "/classes",
                        toolbar: [
                            {
                                text: "添加开课班级",
                                iconCls: "icon-add",
                                handler: function () {
                                    $("#add_class_dlg").dialog("open");
                                    $("#class_combo").combogrid({
                                        panelWidth: 300,
                                        idField: 'id',
                                        textField: 'name',
                                        url: "schedule/notIn/" + courseSchedule.id + "/list/class",
                                        columns: [
                                            [
                                                {field: 'name', title: '名称', align: 'center', width: 80},
                                                {field: 'type', title: '班级类型', align: 'center', width: 60,
                                                    formatter: function (value, row, index) {
                                                        return classtype[value];
                                                    }
                                                },
                                                {field: 'createYear', title: '年级', align: 'center', width: 60}
                                            ]
                                        ],
                                        fitColumns: true
                                    });
                                    $("#add_class_submit").click(function () {
                                        var classId = $('#class_combo').combogrid('getValue');
                                        var g = $('#class_combo').combogrid('grid');
                                        var r = g.datagrid('getSelected');
                                        if (classId) {
                                            $.ajax({
                                                type: 'POST',
                                                url: "schedule/" + courseSchedule.id + "/class/add/" + classId,
                                                dataType: "json",
                                                cache: false,
                                                success: function (data) {
                                                    $("#schedule_class_management_datagrid").oneTime('0.2s', function () {
                                                        $("#schedule_class_management_datagrid").datagrid("appendRow", r);
                                                    });
                                                }
                                            });
                                        }
                                        $('#class_combo').combogrid("clear");
                                        $("#add_class_dlg").dialog("close");
                                    });
                                }
                            }
                        ],
                        columns: [
                            [
                                {field: 'name', title: '名称', align: 'center', width: 80},
                                {field: 'type', title: '班级类型', align: 'center', width: 60,
                                    formatter: function (value, row, index) {
                                        return classtype[value];
                                    }
                                },
                                {field: 'createYear', title: '年级', align: 'center', width: 60},
                                {field: 'id', align: 'center', width: 120,
                                    formatter: function (value, row, index) {
                                        if (row) {
                                            $("#schedule_class_management_datagrid").oneTime('0.2s', function () {
                                                $("#remove_class_" + row.id).linkbutton({
                                                    iconCls: "icon-remove",
                                                    plain: true
                                                });
                                                $("#remove_class_" + row.id).click(function () {
                                                    $.ajax({
                                                        type: 'POST',
                                                        url: "schedule/" + courseSchedule.id + "/class/delete/" + row.id,
                                                        dataType: "json",
                                                        cache: false,
                                                        success: function (data) {
                                                            $("#schedule_class_management_datagrid").oneTime('0.2s', function () {
                                                                $("#schedule_class_management_datagrid").datagrid("deleteRow", index);
                                                            });
                                                        }
                                                    });
                                                });
                                            });
                                            return "<a id='remove_class_" + row.id + "' href='#'>删除开课班级</a>";
                                        }
                                    }
                                }
                            ]
                        ]
                    })

                }
            }
        ],
        columns: [
            [
                {field: 'courseId', width: 120, align: 'center', title: '课程名称',
                    formatter: function (value, row, index) {
                        if (value == 0) {
                            return null;
                        }
                        return row.courseName;
                    },
                    editor: {
                        type: 'combobox',
                        options: {
                            valueField: 'id',
                            textField: 'courseName',
                            url: 'course/list/all',
                            required: true
                        }
                    }
                },
                {field: 'teacherId', width: 80, align: 'center', title: '授课老师',
                    formatter: function (value, row, index) {
                        if (value == 0) {
                            return null;
                        }
                        return row.teacherName;
                    },
                    editor: {
                        type: 'combobox',
                        options: {
                            valueField: 'id',
                            textField: 'name',
                            url: 'teacher/list/all',
                            required: true
                        }
                    }
                },
                {field: 'classroomId', width: 120, align: 'center', title: '授课地点',
                    formatter: function (value, row, index) {
                        if (value == 0) {
                            return null;
                        }
                        return row.classroomLocation;
                    },
                    editor: {
                        type: 'combobox',
                        options: {
                            valueField: 'id',
                            textField: 'classroomLocation',
                            url: 'classroom/list/all',
                            required: false
                        }
                    }
                },
                {field: 'restrictionNumber', width: 60, align: 'center', editor: 'numberbox', title: '开班人数'},
                {field: 'required', width: 60, align: 'center', formatter: booleanFormatter, title: '是否必选',
                    editor: {
                        type: 'checkbox',
                        options: {
                            on: 1,
                            off: 0
                        }
                    }
                },
                {field: 'restrictionGrade', width: 80, align: 'center', editor: 'text', title: '开课年级'}
            ]
        ],
        onClickRow: function (rowIndex, rowData) {
            if (editIndex != rowIndex) {
                if (endEditing()) {
                    $('#schedule_datagrid').datagrid('selectRow', rowIndex)
                        .datagrid('beginEdit', rowIndex);
                    initialPropertyData(rowData);
                    editIndex = rowIndex;
                } else {
                    $('#schedule_datagrid').datagrid('selectRow', rowIndex);
                }
            }
        },
        onUnselect: function (rowIndex, rowData) {
            var propertyRows = {
                total: 0,
                rows: []
            };
            $("#schedule_property").propertygrid("loadData", propertyRows);
        },
        loadFilter: schedulePageLoadFilter
    });

    $("#schedule_property").propertygrid({
        title: '课程编排属性',
        showGroup: true,
        scrollbarSize: 0,
        fit: true,
        columns: [
            [
                {field: 'name', title: '属性', width: 100, sortable: true},
                {field: 'value', title: '值', width: 100, resizable: false, formatter: booleanFormatter}
            ]
        ]
    });


});

function schedulePageLoadFilter(data) {

    if (typeof data.length == 'number' && typeof data.splice == 'function') {    // is array
        data = {
            total: data.length,
            rows: data
        }
    }
    var dg = $(this);
    var opts = dg.datagrid('options');
    var pager = dg.datagrid('getPager');
    pager.pagination({
        pageList: [10, 20, 30],//可以设置每页记录条数的列表
        beforePageText: '第',//页数文本框前显示的汉字
        afterPageText: '页    共 {pages} 页',
        displayMsg: '当前显示 {from} - {to} 条记录   共 {total} 条记录',
        onSelectPage: function (pageNum, pageSize) {
            if (endEditing()) {
                opts.pageNumber = pageNum;
                opts.pageSize = pageSize;
                pager.pagination('refresh', {
                    pageNumber: pageNum,
                    pageSize: pageSize
                });

                dg.datagrid('loadData', data);
            }
        }
    });
    if (!data.originalRows) {
        data.originalRows = (data.rows);
    }
    var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
    var end = start + parseInt(opts.pageSize);
    data.rows = (data.originalRows.slice(start, end));
    return data;

}

//初始化课程编排属性表
function initialPropertyData(rowData) {
    var propertyRows = {
        total: 20,
        rows: [
            {name: "第一学期", value: rowData.firstTerm, group: "开课学期",
                editor: {type: "checkbox", options: {on: 1, off: 0}}},
            {name: "第二学期", value: rowData.secondTerm, group: "开课学期",
                editor: {type: "checkbox", options: {on: 1, off: 0}}},
            {name: "第一学段", value: rowData.firstSection, group: "开课学段",
                editor: {type: "checkbox", options: {on: 1, off: 0}}},
            {name: "第二学段", value: rowData.secondSection, group: "开课学段",
                editor: {type: "checkbox", options: {on: 1, off: 0}}},
            {name: "第三学段", value: rowData.thirdSection, group: "开课学段",
                editor: {type: "checkbox", options: {on: 1, off: 0}}},
            {name: "周一", value: rowData.monday, group: "开课周期",
                editor: {type: "checkbox", options: {on: 1, off: 0}}},
            {name: "周二", value: rowData.tuesday, group: "开课周期",
                editor: {type: "checkbox", options: {on: 1, off: 0}}},
            {name: "周三", value: rowData.wednesday, group: "开课周期",
                editor: {type: "checkbox", options: {on: 1, off: 0}}},
            {name: "周四", value: rowData.thursday, group: "开课周期",
                editor: {type: "checkbox", options: {on: 1, off: 0}}},
            {name: "周五", value: rowData.friday, group: "开课周期",
                editor: {type: "checkbox", options: {on: 1, off: 0}}},
            {name: "周六", value: rowData.saturday, group: "开课周期",
                editor: {type: "checkbox", options: {on: 1, off: 0}}},
            {name: "周日", value: rowData.sunday, group: "开课周期",
                editor: {type: "checkbox", options: {on: 1, off: 0}}},
            {name: "第一节课", value: rowData.firstLesson, group: "开课节次",
                editor: {type: "checkbox", options: {on: 1, off: 0}}},
            {name: "第二节课", value: rowData.secondLesson, group: "开课节次",
                editor: {type: "checkbox", options: {on: 1, off: 0}}},
            {name: "第三节课", value: rowData.thirdLesson, group: "开课节次",
                editor: {type: "checkbox", options: {on: 1, off: 0}}},
            {name: "第四节课", value: rowData.forthLesson, group: "开课节次",
                editor: {type: "checkbox", options: {on: 1, off: 0}}},
            {name: "第五节课", value: rowData.fifthLesson, group: "开课节次",
                editor: {type: "checkbox", options: {on: 1, off: 0}}},
            {name: "第六节课", value: rowData.sixthLesson, group: "开课节次",
                editor: {type: "checkbox", options: {on: 1, off: 0}}},
            {name: "第七节课", value: rowData.seventhLesson, group: "开课节次",
                editor: {type: "checkbox", options: {on: 1, off: 0}}},
            {name: "第八节课", value: rowData.eighthLesson, group: "开课节次",
                editor: {type: "checkbox", options: {on: 1, off: 0}}}
        ]
    };
    $("#schedule_property").propertygrid("loadData", propertyRows);
};

/*
 *以下为编辑列表时的处理方法
 */
var editIndex = undefined;

function endEditing() {
    if (editIndex == undefined) {
        return true
    }
    if ($('#schedule_datagrid').datagrid('validateRow', editIndex)) {
        var isChange = false;
        var propertySelected = $("#schedule_property").propertygrid("getSelected");
        if (propertySelected) {
            var editRowIndex = $("#schedule_property").propertygrid("getRowIndex", propertySelected);
            $("#schedule_property").propertygrid("endEdit", editRowIndex);
        }
        var propertyChanges = $("#schedule_property").propertygrid("getChanges");
        if (propertyChanges.length != 0) {
            for (var i = 0; i < propertyChanges.length; i++) {
                var property = propertyChanges[i];
                switch (property.name) {
                    case "第一学期":
                        $('#schedule_datagrid').datagrid('getRows')[editIndex].firstTerm = property.value;
                        break;
                    case "第二学期":
                        $('#schedule_datagrid').datagrid('getRows')[editIndex].secondTerm = property.value;
                        break;
                    case "第一学段":
                        $('#schedule_datagrid').datagrid('getRows')[editIndex].firstSection = property.value;
                        break;
                    case "第二学段":
                        $('#schedule_datagrid').datagrid('getRows')[editIndex].secondSection = property.value;
                        break;
                    case "第三学段":
                        $('#schedule_datagrid').datagrid('getRows')[editIndex].thirdSection = property.value;
                        break;
                    case "周一":
                        $('#schedule_datagrid').datagrid('getRows')[editIndex].monday = property.value;
                        break;
                    case "周二":
                        $('#schedule_datagrid').datagrid('getRows')[editIndex].tuesday = property.value;
                        break;
                    case "周三":
                        $('#schedule_datagrid').datagrid('getRows')[editIndex].wednesday = property.value;
                        break;
                    case "周四":
                        $('#schedule_datagrid').datagrid('getRows')[editIndex].thursday = property.value;
                        break;
                    case "周五":
                        $('#schedule_datagrid').datagrid('getRows')[editIndex].friday = property.value;
                        break;
                    case "周六":
                        $('#schedule_datagrid').datagrid('getRows')[editIndex].saturday = property.value;
                        break;
                    case "周日":
                        $('#schedule_datagrid').datagrid('getRows')[editIndex].sunday = property.value;
                        break;
                    case "第一节课":
                        $('#schedule_datagrid').datagrid('getRows')[editIndex].firstLesson = property.value;
                        break;
                    case "第二节课":
                        $('#schedule_datagrid').datagrid('getRows')[editIndex].secondLesson = property.value;
                        break;
                    case "第三节课":
                        $('#schedule_datagrid').datagrid('getRows')[editIndex].thirdLesson = property.value;
                        break;
                    case "第四节课":
                        $('#schedule_datagrid').datagrid('getRows')[editIndex].forthLesson = property.value;
                        break;
                    case "第五节课":
                        $('#schedule_datagrid').datagrid('getRows')[editIndex].fifthLesson = property.value;
                        break;
                    case "第六节课":
                        $('#schedule_datagrid').datagrid('getRows')[editIndex].sixthLesson = property.value;
                        break;
                    case "第七节课":
                        $('#schedule_datagrid').datagrid('getRows')[editIndex].seventhLesson = property.value;
                        break;
                    case "第八节课":
                        $('#schedule_datagrid').datagrid('getRows')[editIndex].eighthLesson = property.value;
                        break;
                }
            }
            isChange = true;
        }

        var course_ed = $('#schedule_datagrid').datagrid('getEditor', {index: editIndex, field: 'courseId'});
        var teacher_ed = $('#schedule_datagrid').datagrid('getEditor', {index: editIndex, field: 'teacherId'});
        var classroom_ed = $('#schedule_datagrid').datagrid('getEditor', {index: editIndex, field: 'classroomId'});
        var courseName = $(course_ed.target).combobox('getText');
        var teacherName = $(teacher_ed.target).combobox('getText');
        var classroomLocation = $(classroom_ed.target).combobox('getText');
        $('#schedule_datagrid').datagrid('getRows')[editIndex]['courseName'] = courseName;
        $('#schedule_datagrid').datagrid('getRows')[editIndex]['teacherName'] = teacherName;
        $('#schedule_datagrid').datagrid('getRows')[editIndex]['classroomLocation'] = classroomLocation;

        $('#schedule_datagrid').datagrid('endEdit', editIndex);
        var infoChanges = $('#schedule_datagrid').datagrid("getChanges");
        if (infoChanges.length != 0) {
            isChange = true;
        }

        if ($('#schedule_datagrid').datagrid('getData').rows[editIndex].courseId == 0) {
            $.ajax({
                type: 'POST',
                url: "schedule/delete/" + $('#schedule_datagrid').datagrid('getData').rows[editIndex].id,
                dataType: "json",
                cache: false,
                success: function (data) {

                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
                }
            });
            $('#schedule_datagrid')
                .datagrid('deleteRow', editIndex);
            $('#schedule_datagrid').datagrid("acceptChanges");
            editIndex = undefined;
            return true;
        }

        if (isChange == true) {
            var updateData = $('#schedule_datagrid').datagrid('getData').rows[editIndex];
            $.ajax({
                type: 'POST',
                data: updateData,
                url: "schedule/update",
                dataType: "json",
                cache: false,
                success: function (data) {
                    //$('#schedule_datagrid').oneTime("0.2s",function(){
                    $('#schedule_datagrid').datagrid("acceptChanges");
                    editIndex = undefined;
                    //});
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
                    $('#schedule_datagrid').datagrid("rejectChanges");
                    $("#schedule_property").propertygrid("rejectChanges");
                    editIndex = undefined;
                }
            });
        }

        editIndex = undefined;
        return true;
    } else {
        return false;
    }
};

//布尔值格式化显示
function booleanFormatter(value, row, index) {
    if (String(value) == "1") {
        return "是";
    }
    return "否";
};
